package com.btl.boot.core.util;

import com.btl.boot.core.dto.TreeNode;

import java.util.*;

/**
 * 树节点构造
 *
 * @author zhukai
 * @since 2025/5/25 18:58
 */
public class TreeUtils {
    public static List<TreeNode<Long, String>> build(List<TreeNode<Long, String>> allNodes) {
        Map<Long, TreeNode<Long, String>> nodeMap = new TreeMap<>();
        List<TreeNode<Long, String>> roots = new ArrayList<>();
        allNodes.forEach(node -> {
            if (Objects.isNull(node.getChildren())) {
                node.setChildren(new ArrayList<>());
            }
            nodeMap.put(node.getId(), node);
            if (node.getParentId() == 0) {
                roots.add(node);
            }
        });
        allNodes.forEach(node -> {
            if (node.getParentId() != 0) {
                TreeNode<Long, String> parent = nodeMap.get(node.getParentId());
                if (Objects.nonNull(parent)) {
                    parent.getChildren().add(node);
                }
            }
        });

        // 对树进行递归排序
        sortTree(roots);
        return roots;
    }

    private static void sortTree(List<TreeNode<Long, String>> nodes) {
        if (nodes == null || nodes.isEmpty()) {
            return;
        }
        // 对当前层排序
        nodes.sort(Comparator.comparing(TreeNode::getSort));
        // 递归排序子节点
        nodes.forEach(node -> {
            if (node.getChildren() != null && !node.getChildren().isEmpty()) {
                sortTree(node.getChildren());
            }
        });
    }
}
